#include<iostream>
#include<memory>
#include<vector>
#include "UdpServer.hpp"
#include "log.hpp"

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << "prot[1024+]\n" << std::endl;
}
std::string Handler(const std::string& str, const std::string& clientip, const uint16_t& clientport)
{
    std::cout << "[" << clientip << ":" << clientport << "]#" << str << std::endl;
    std::string res = "Server get a message: ";
    res += str;
    //std::cout << res << std::endl;

    return res;
}
bool SafeCheck(const std::string &cmd)
{
    std::vector<std::string> key_word = {"rm", "mv", "cp", "kill", "sudo", "unlink", "uninstall", "yum", "top", "while"};
    for(auto &word : key_word)
    {
        auto pos = cmd.find(word);
        if(pos != std::string::npos) return false;
    }
    return true;
}
std::string ExcuteCommand(const std::string& cmd)
{
    std::cout << "get a request cmd: " << cmd <<std::endl;
    if(!SafeCheck(cmd)) return "Band man";
    FILE* fp = popen(cmd.c_str(), "r");
    if(nullptr == fp)
    {
        perror("popen");
        return "error";
    }
    char buffer[4096];
    std::string ret;
    while(true)
    {
        char* res = fgets(buffer, sizeof(buffer), fp);
        if(res == nullptr)break;
        ret += buffer;
    }

    pclose(fp);
    return ret;
}
int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }
    uint16_t prot = std::stoi(argv[1]);
    std::unique_ptr<UdpServer> svr(new UdpServer(prot));
    
    svr->Init();
    svr->Run();

    return 0;
}
